from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
from utils.common_response import APIResponse


# 验证码获取  # 开放的接口
def get_captcha(request):
    new_key = CaptchaStore.generate_key()
    captcha_url = captcha_image_url(new_key)
    # 返回一个验证码的key，和验证码图片的url
    return APIResponse(captcha_key=new_key, captcha_url=captcha_url)


# 校验验证码函数
def _verify_captcha(captcha_key, captcha_value):
    # 根据验证码的key去校验验证码的值
    try:
        captcha = CaptchaStore.objects.get(hashkey=captcha_key)
        if captcha.response == captcha_value:
            return True
        else:
            return False
    except CaptchaStore.DoesNotExist:
        return False
